package com.myapp.actions.client;

import com.myapp.MyApp;
import com.mydatastore.ClientDataStore;
import com.mydatastore.mysql.client.ClientDataStoreMySQL;
import com.mydatastore.DataStoreException;
import com.mydatastore.entity.Client;
import com.mydatastore.entity.Sex;
import com.myweb.WebAction;
import com.myweb.WebException;
import com.myweb.WebRequest;
import com.myweb.WebResponse;
import com.myweb.annotation.Action;
import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.PersistenceUnit;
import javax.servlet.ServletException;
import javax.transaction.UserTransaction;

@Action(url = "clients/add")
public class AddClient implements WebAction {

  private Client client;
  private EntityManagerFactory emf = Persistence.createEntityManagerFactory("MyWebPU");

  @Override
  public void validate(WebRequest request) throws WebException {
    String firstName = request.getStringNN("firstName");
    String middleName = request.getStringNN("middleName");
    String lastName = request.getStringNN("lastName");
    int age = request.getIntegerNN("age");
    Sex sex = Sex.valueOf(request.getStringNN("sex").toUpperCase());
    client = new Client(firstName, middleName, lastName, age, sex);
  }

  @Override
  public void process(WebRequest req, WebResponse res) throws WebException {
    System.out.println(emf);  
    EntityManager em = null;
    try {
      em.getTransaction().begin();
      em = emf.createEntityManager();
      em.persist(client);
      em.getTransaction().commit();

    } catch (Exception ex) {
      System.out.println("ssssssssddxxxxd");
      throw new WebException(ex);
    } finally {
      if (em != null) {
        em.close();
      }
    }
  }

  @Override
  public String getRenderer() {
    return "/WEB-INF/client/addclient.jsp";
  }
}
